package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    private IVoucherOrderService proxy;

    //在类初始化后执行
    @PostConstruct
    private void init() {

        SECKILL_ORDER_EXECUTOR.submit(new VocherOrderHandler());
    }

    private class VocherOrderHandler implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    //取订单
                    VoucherOrder order = orderTasks.take();
                    handleVoucherOrder(order);
                } catch (Exception e) {
                    log.info("处理订单异常", e);
                }
            }
        }


        //处理订单
        private void handleVoucherOrder(VoucherOrder voucherOrder) {
            Long userId = voucherOrder.getUserId();
            RLock lock = redissonClient.getLock("lock:order:" + userId);
            boolean tryLock = lock.tryLock();
            if (!tryLock) {
                log.error("不允许重复下单");
                return;
            }
            //传进去整个订单
            try {
                proxy.getResult(voucherOrder);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }

        }
    }

    private final static DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    /**
     * 利用消息队列来优化秒杀，为什么使用了消息队列就不需要使用锁了:
     * 因为锁是为了处理并发执行，访问资源，不用还出现超卖等现象，
     * 而消息队列将并发执行的线程转化为了串行执行，不需要竞争资源便不需要使用锁了
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        log.info("进入秒杀下单");
        Long execute = stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                UserHolder.getUser().getId());
        //不等于0则可能为1或2
        if (execute != 0) {
            return Result.fail(execute == 1 ? "库存不足" : "已经下单");
        }
        long orderId = redisIdWorker.nextId("order");
        //将订单保存到消息队列
        VoucherOrder voucherOrder = VoucherOrder.builder()
                .id(orderId)
                .userId(UserHolder.getUser().getId())
                .voucherId(voucherId)
                .build();
        orderTasks.add(voucherOrder);
        //获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        //下单成功
        return Result.ok(orderId);
    }
    /*@Override
    public Result seckillVoucher(Long voucherId) {
        log.info("进入秒杀");
        //查询优惠劵信息
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        //判断时间对不对
        if (voucher.getCreateTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀还未开始");
        }
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀已经过时");
        }
        //判断数据库库存是否充足

        if (voucher.getStock() < 1) {
            return Result.fail("库存不足");
        }
        Long userId = UserHolder.getUser().getId();
        //利用redis锁
        //SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order" + userId, stringRedisTemplate);
        RLock lock = redissonClient.getLock("order" + userId);
        boolean tryLock = lock.tryLock();
        if (!tryLock) {
            return Result.fail("不能多次购买");
        }
        //此事获取锁成功


        try {
            //synchronized (userId.toString().intern()) {
            //如果这个的话事务不会生效，因为事务是作用于给spring代理的代理对象
            //我们调用这个方法是目标对象，是我们自己使用的,因此事务不会生效
            //因此我们要利用代理对象使用这个方法，需要引入依赖和在启动类上声明
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.getResult(voucherId);
            // }
        } finally {
            lock.unlock();
        }
    }*/

    /**
     * 锁加方法上是给所有给对象加锁，加在调用的方法上，是给调用该对象单独加一个锁
     */
    @Transactional
    public void getResult(VoucherOrder voucherOrder) {
        //判断用户是否已经下了一单
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        Integer count = query().eq("user_id", userId)
                .eq("voucher_id", voucherId )
                .count();
        if (count > 0) {
            log.info("用户已经下了一单");
        }

        //减一
        boolean success = seckillVoucherService
                .update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0) //cas锁
                .update();
        if (!success) {
            log.info("库存不足");
        }
        save(voucherOrder);



    }
}
